package com.jsmile.cloud.msgcenter.websocket;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.jsmile.cloud.msgcenter.api.enums.MsgTypeEnum;
import com.jsmile.cloud.msgcenter.api.req.WebSocketMsg;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{userId}")
public class WebSocketServer {

    private static final ConcurrentHashMap<String, CopyOnWriteArraySet<Session>> sessionPools = new ConcurrentHashMap<>();

    // 发送消息
    public static void sendMessage(Session session, WebSocketMsg webSocketMsg) throws IOException {
        if (session != null) {
            synchronized (session) {
                if (session.isOpen()) {
                    session.getAsyncRemote().sendText(JSON.toJSONString(webSocketMsg));
                }
            }
        }
    }

    public static void sendInfo(String userId, WebSocketMsg webSocketMsg) {
        CopyOnWriteArraySet<Session> sessionList = sessionPools.get(userId);
        if (CollectionUtils.isEmpty(sessionList)) {
            return;
        }
        sessionList.stream().forEach(session -> {
            try {
                sendMessage(session, webSocketMsg);
            } catch (Exception e) {
                log.info("推送消息异常：{}", ExceptionUtils.getStackTrace(e));
            }

        });
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) {
        CopyOnWriteArraySet<Session> sessions = sessionPools.get(userId);
        if (null == sessions) {
            sessions = new CopyOnWriteArraySet();
        }
        sessions.add(session);
        sessionPools.put(userId, sessions);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("userId") String userId, Session session) {
        CopyOnWriteArraySet<Session> sessionList = sessionPools.get(userId);
        if (CollectionUtils.isEmpty(sessionList)) {
            return;
        }
        if (null != session) {
            sessionList.remove(session);
        }
    }

    /**
     * 收到客户端消息后调用的方法（暂不实现）
     */
    @OnMessage
    public void onMessage(@PathParam("userId") String userId, Session session, String message) {
        try {
            // 心跳检测才返回数据
            if (MsgTypeEnum.HEART_CHECK_NOTIFY.getValue().equals(JSON.parseObject(message, WebSocketMsg.class).getMsgType())) {
                sendMessage(session, WebSocketMsg.builder().msgType(MsgTypeEnum.HEART_CHECK_NOTIFY.getValue()).msgBody("ok").build());
            }
        } catch (Exception e) {
            log.info("心跳检测消息异常：{}", ExceptionUtils.getStackTrace(e));
        }
    }

    @OnError
    public void onError(@PathParam("userId") String userId, Session session, Throwable error) {
        // log.error("用户错误:" + userId + ",原因:" + ExceptionUtils.getStackTrace(error));
    }

}
